package top.lixunda.ecommerce.server.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import top.lixunda.common.utils.ObjectValidators;
import top.lixunda.ecommerce.server.business.BaseServiceImpl;
import top.lixunda.ecommerce.server.business.api.entity.BusinessConstants;
import top.lixunda.ecommerce.server.business.api.entity.cache.CacheLoginUser;
import top.lixunda.ecommerce.server.business.api.entity.dto.PageDTO;
import top.lixunda.ecommerce.server.user.api.entity.db.MessageDO;
import top.lixunda.ecommerce.server.user.api.entity.dto.MessageInsertDTO;
import top.lixunda.ecommerce.server.user.api.entity.dto.MessageQueryDTO;
import top.lixunda.ecommerce.server.user.mapper.MessageMapper;
import top.lixunda.ecommerce.server.user.service.IMessageService;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Xumda
 * @since 2020-04-12
 */
@Service
public class MessageServiceImpl extends BaseServiceImpl<MessageMapper, MessageDO>
        implements IMessageService {

    /**
     * 保存一条发送的消息
     *
     * @param list 保存消息使用DTO
     * @return 返回保存后的数据
     */
    @Override
    public List<MessageDO> addMessages(List<MessageInsertDTO> list) {
        if (ObjectValidators.isEmpty(list)) {
            throw getAppException("参数不能为空");
        }

        LocalDateTime localDateTime = LocalDateTime.now();
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        List<MessageDO> insertList = list.stream()
                .filter(Objects::nonNull)
                .map(item -> {
                    MessageDO messageDO = new MessageDO();
                    BeanUtils.copyProperties(item, messageDO);
                    messageDO.setCreateTime(localDateTime)
                            .setCreateUserId(cacheLoginUser.getAccount())
                            .setCreateUserName(cacheLoginUser.getName())
                            .setCreateUserType(cacheLoginUser.getType());
                    return messageDO;
                }).collect(Collectors.toList());
        if (ObjectValidators.isEmpty(insertList)) {
            throw getAppException("参数不能为空");
        }
        boolean success = this.saveBatch(insertList);
        if (!success) {
            throw getAppException("保存数据失败");
        }
        return insertList;
    }

    /**
     * 根据消息id查询消息
     *
     * @param id 消息id
     * @return 消息数据
     */
    @Override
    public MessageDO queryById(Integer id) {
        if (ObjectValidators.isEmpty(id)) {
            throw getAppException("消息编号不能为空");
        }
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        MessageDO messageDO = this.getOne(new LambdaQueryWrapper<MessageDO>()
                .eq(MessageDO::getId, id)
                .eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                .eq(MessageDO::getUserType, cacheLoginUser.getType()), false);
        if (ObjectValidators.isEmpty(messageDO)) {
            throw getAppException("消息不存在");
        }
        return messageDO;
    }

    /**
     * 根据多个id查询消息数据
     *
     * @param ids 多个消息id
     * @return 消息数据
     */
    @Override
    public List<MessageDO> queryByIds(List<Integer> ids) {
        if (ObjectValidators.isEmpty(ids)) {
            throw getAppException("消息编号不能为空");
        }
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        return this.list(new LambdaQueryWrapper<MessageDO>()
                .in(MessageDO::getId, ids)
                .eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                .eq(MessageDO::getUserType, cacheLoginUser.getType()));
    }

    /**
     * 根据条件分页查询消息数据
     *
     * @param pageDTO 分页DTO
     * @return 分页数据
     */
    @Override
    public IPage<MessageDO> queryByPageWrapper(PageDTO<MessageDO, MessageQueryDTO> pageDTO) {
        if (ObjectValidators.isEmpty(pageDTO)) {
            throw getAppException("参数不能为空");
        }
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        return this.page(pageDTO.getPage(), pageDTO.getWrapper(wrapper ->
                wrapper.eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                        .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                        .eq(MessageDO::getUserType, cacheLoginUser.getType())));
    }

    /**
     * 分页条件查询未消费的消息数据
     *
     * @param pageDTO 分页DTO
     * @return 分页数据
     */
    @Override
    public IPage<MessageDO> queryNoConsumeByPageWrapper(PageDTO<MessageDO, MessageQueryDTO> pageDTO) {
        if (ObjectValidators.isEmpty(pageDTO)) {
            throw getAppException("参数不能为空");
        }
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        return this.page(pageDTO.getPage(), pageDTO.getWrapper(wrapper ->
                wrapper.eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                        .eq(MessageDO::getConsumeFlag, BusinessConstants.MESSAGE_CONSUME_FALSE)
                        .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                        .eq(MessageDO::getUserType, cacheLoginUser.getType())));
    }

    /**
     * 查询所以的未消费消息数据
     *
     * @return 所有未消费的消息数据
     */
    @Override
    public List<MessageDO> queryAllNoConsume() {
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        return this.list(new LambdaQueryWrapper<MessageDO>()
                .eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                .eq(MessageDO::getConsumeFlag, BusinessConstants.MESSAGE_CONSUME_FALSE)
                .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                .eq(MessageDO::getUserType, cacheLoginUser.getType()));
    }

    /**
     * 查询未消费消息数据个数
     *
     * @return 未消费消息个数
     */
    @Override
    public Integer queryNoConsumeCount() {
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        return this.count(new LambdaQueryWrapper<MessageDO>()
                .eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                .eq(MessageDO::getConsumeFlag, BusinessConstants.MESSAGE_CONSUME_FALSE)
                .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                .eq(MessageDO::getUserType, cacheLoginUser.getType()));
    }

    /**
     * 根据id消费消息数据
     *
     * @param ids 多个消息数据编号
     * @return 消费后的消息数据
     */
    @Override
    public List<MessageDO> consumeMessageByIds(List<Integer> ids) {
        if (ObjectValidators.isEmpty(ids)) {
            throw getAppException("参数不能为空");
        }
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        List<MessageDO> list = this.list(new LambdaQueryWrapper<MessageDO>()
                .in(MessageDO::getId, ids)
                .eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                .eq(MessageDO::getConsumeFlag, BusinessConstants.MESSAGE_CONSUME_FALSE)
                .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                .eq(MessageDO::getUserType, cacheLoginUser.getType()));
        if (ObjectValidators.isEmpty(list)) {
            throw getAppException("数据不存在");
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        list.forEach(item ->
                item.setConsumeType(BusinessConstants.MESSAGE_CONSUME_TYPE_IDS)
                        .setConsumeTime(localDateTime)
                        .setConsumeFlag(BusinessConstants.MESSAGE_CONSUME_TRUE));
        boolean success = this.updateBatchById(list);
        if (!success) {
            throw getAppException("更新数据失败");
        }
        return list;
    }

    /**
     * 消费所有消息数据
     *
     * @return 消费所有消息数据
     */
    @Override
    public List<MessageDO> consumeAll() {
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        List<MessageDO> list = this.list(new LambdaQueryWrapper<MessageDO>()
                .eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                .eq(MessageDO::getConsumeFlag, BusinessConstants.MESSAGE_CONSUME_FALSE)
                .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                .eq(MessageDO::getUserType, cacheLoginUser.getType()));
        if (ObjectValidators.isEmpty(list)) {
            return Collections.emptyList();
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        list.forEach(item ->
                item.setConsumeType(BusinessConstants.MESSAGE_CONSUME_TYPE_ALL)
                        .setConsumeTime(localDateTime)
                        .setConsumeFlag(BusinessConstants.MESSAGE_CONSUME_TRUE));
        boolean success = this.updateBatchById(list);
        if (!success) {
            throw getAppException("更新数据失败");
        }
        return list;
    }

    /**
     * 删除消息
     *
     * @param ids 消息编号列表
     * @return 移除的消息
     */
    @Override
    public List<MessageDO> removeByIds(List<Integer> ids) {
        if (ObjectValidators.isEmpty(ids)) {
            throw getAppException("参数不能为空");
        }
        CacheLoginUser cacheLoginUser = currentLoginUserCacheNotNull();
        List<MessageDO> list = this.list(new LambdaQueryWrapper<MessageDO>()
                .in(MessageDO::getId, ids)
                .eq(MessageDO::getUsable, BusinessConstants.USEABLE_TRUE)
                .eq(MessageDO::getConsumeFlag, BusinessConstants.MESSAGE_CONSUME_FALSE)
                .eq(MessageDO::getUserId, cacheLoginUser.getAccount())
                .eq(MessageDO::getUserType, cacheLoginUser.getType()));
        if (ObjectValidators.isEmpty(list)) {
            throw getAppException("数据不存在");
        }
        list.forEach(item ->
                item.setUsable(BusinessConstants.USEABLE_FALSE));
        boolean success = this.updateBatchById(list);
        if (!success) {
            throw getAppException("移除数据失败");
        }
        return list;
    }
}
